package org.codefinger.dao;

import java.util.List;
import java.util.Map;
import java.util.Set;

import org.codefinger.json.util.Lang;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class SpringQuery extends Query implements InitializingBean, ApplicationContextAware {

	protected DaoUtil				daoUtil;

	protected String				sql;

	protected Query					query;

	protected ApplicationContext	applicationContext;

	public SpringQuery() {
		super(null);
	}

	public void setDaoUtil(DaoUtil daoUtil) {
		this.daoUtil = daoUtil;
	}

	public void setSql(String sql) {
		this.sql = sql;
	}

	@Override
	public QueryChain putParam(String name, Object value) {
		return query.putParam(name, value);
	}

	@Override
	public QueryChain putParams(Map<String, Object> params) {
		return query.putParams(params);
	}

	@Override
	public QueryChain setParams(Object... params) {
		return query.setParams(params);
	}

	@Override
	public QueryChain setOrders(int... orders) {
		return query.setOrders(orders);
	}

	@Override
	public QueryChain setPage(int pageIndex, int pageSize) {
		return query.setPage(pageIndex, pageSize);
	}

	@Override
	public <T> T fetch(Class<T> clas) {
		return query.fetch(clas);
	}

	@Override
	public <T> List<T> getList(Class<T> clas) {
		return query.getList(clas);
	}

	@Override
	public <T> Set<T> getSet(Class<T> clas) {
		return query.getSet(clas);
	}

	@Override
	public Map<String, Object> fetch() {
		return query.fetch();
	}

	@Override
	public <T> List<Map<String, Object>> getMapList() {
		return query.getMapList();
	}

	@Override
	public <T> Set<Map<String, Object>> getMapSet() {
		return query.getMapSet();
	}

	@Override
	public <T> T getUnique(DaoType<T> type) {
		return query.getUnique(type);
	}

	@Override
	public <T> T getResult(QueryCallback<T> queryCallback) {
		return query.getResult(queryCallback);
	}

	@Override
	public int queryCount() {
		return query.queryCount();
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		if (daoUtil == null) {
			daoUtil = applicationContext.getBean(DaoUtil.class);
		}
		if (sql == null) {
			throw Lang.makeThrow("Please set sql for the %s bean.", SpringQuery.class);
		}
		this.query = daoUtil.createQuery(sql);
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}
}
